package org.rainwalk.library.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.rainwalk.library.api.auth.Auth;
import org.rainwalk.library.api.log.ApiLog;
import org.rainwalk.library.api.model.Response;
import org.rainwalk.library.api.model.ResponseCode;
import org.rainwalk.library.entity.Storage;
import org.rainwalk.library.model.dto.DirectoryAddDTO;
import org.rainwalk.library.model.vo.DirectoryVO;
import org.rainwalk.library.model.vo.RouteVO;
import org.rainwalk.library.model.vo.StorageVO;
import org.rainwalk.library.service.IStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 目录相关接口
 *
 * @author 趁雨行 2021/7/6
 */
@RestController
@RequestMapping("/directory")
@RequiredArgsConstructor(onConstructor_={@Autowired})
public class DirectoryController {

    private final IStorageService storageService;

    @Auth
    @ApiLog("新建目录")
    @PostMapping
    public Response add(@Validated DirectoryAddDTO directoryAddDTO) {
        StorageVO storageVO = storageService.addDirectory(directoryAddDTO);
        if (storageVO == null) {
            return Response.fail(ResponseCode.PARAMS_VERITY_FAIL, "新建目录失败");
        }
        return Response.success(storageVO);
    }

    @ApiLog("路径导航")
    @GetMapping("/{id}")
    public Response to(@PathVariable Long id, @RequestParam boolean onlyDirectory) {
        if (id != 0) {
            LambdaQueryWrapper<Storage> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Storage::getId, id)
                    .eq(Storage::getIsDirectory, true);
            if (id < 0 || storageService.count(queryWrapper) == 0) {
                return Response.fail(ResponseCode.PARAMS_VERITY_FAIL, "目录不存在");
            }
        }
        List<StorageVO> vos = storageService.toDirectory(id, onlyDirectory);
        DirectoryVO directoryVO = storageService.getRoute(id);
        RouteVO routeVO = new RouteVO();
        routeVO.setRoute(directoryVO);
        routeVO.setChildren(vos);
        return Response.success(routeVO);
    }
}
